package com.coderman.basketball.statistics.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * date: 2021/5/25
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
@Slf4j
public class GameEventHandlerContainer implements ApplicationContextAware {
    /**
     * 存储消息消费的事件处理器
     */
    private static Map<String, EventHandler> eventHandlerMap = new HashMap<>();

    /**
     * 根据topic#tag，返回对应的消息事件handler
     *
     * @param eventTag
     * @return
     */
    public EventHandler getEventHandler(String eventTag) {
        return eventHandlerMap.get(eventTag);
    }

    /**
     * 重写ApplicationContextAware的方法，将event handler和起对应的tag进行绑定，并存入map中
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansOfMQHandler = applicationContext.getBeansWithAnnotation(EventTag.class);
        for (Map.Entry<String, Object> entry : beansOfMQHandler.entrySet()) {
            EventTag eventTag = AopUtils.getTargetClass(entry.getValue()).getAnnotation(EventTag.class);
            eventHandlerMap.put(eventTag.eventType(), (EventHandler) entry.getValue());
        }
    }
}
